const UserModel = require("../model/favorites");
const jwt = require("jsonwebtoken");
const {
    secret
} = require("../config");
const catchError = require("../utils/catchError");

class Favorites {
    async addFav(ctx) {
        let {
            username,
            cartName,
            cartDes,
            cartImg,
            cartType,
            cartPrice,
            cartSpc,
        } = ctx.request.body;

        let data = await UserModel.create({
            username,
            cartName,
            cartDes,
            cartImg,
            cartType,
            cartPrice,
            cartSpc,
        });

        ctx.body = {
            code: 0,
            msg: "添加收藏夹成功",
        };
    }

    async delFav(ctx) {
        let {
            cartName
        } = ctx.request.body;

        let nameArr = cartName.split(',')

        await UserModel.deleteMany({
            cartName: {
                $in: nameArr
            }
        })

        ctx.body = {
            code: 0,
            msg: "移出收藏夹成功",
        };
    }

    async getFav(ctx) {
        let {
            cartName
        } = ctx.request.body;

        let data = await UserModel.findOne({ cartName })
        if(!data){
            return ctx.body = {
                code: 1,
                msg: "不在收藏夹",
            };
        }
        ctx.body = {
            code: 0,
            msg: "在收藏夹",
        };
    }

    async getUserFav(ctx) {
        let {
            username
        } = ctx.request.body;

        let data = await UserModel.find({username})
        if(!data){
            return ctx.body = {
                code: 1,
                msg: "不在收藏夹",
            };
        }
        ctx.body = {
            code: 0,
            msg: "获取用户收藏",
            data: {...data}
        };
    }
}

module.exports = new Favorites();